package com.zx.predicates;

import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.handler.predicate.AbstractRoutePredicateFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;

import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;

/**
 * 自定义路由断言工厂类
 * 要求：1、名字必须是配置+RoutePredicateFactory
 * 2、必须继承AbstractRoutePredicateFactory<配置类>
 *
 * @author jack.wu
 * @version 1.0
 * @date 2020-03-09
 */
//@Component
public class AgeRoutePredicateFactory extends AbstractRoutePredicateFactory<AgeRoutePredicateFactory.Config> {

    public AgeRoutePredicateFactory() {
        super(AgeRoutePredicateFactory.Config.class);
    }

    /**
     * 读取配置文件的参数，并赋值其属性上
     */
    @Override
    public List<String> shortcutFieldOrder() {
        // 这个位置的顺序必须跟配置文件中的值顺序对应
        return Arrays.asList("minAge", "maxAge");
    }

    @Override
    public Predicate<ServerWebExchange> apply(AgeRoutePredicateFactory.Config config) {
        return serverWebExchange -> {
            // 1、接受前台穿过来age参数
            String ageStr = serverWebExchange.getRequest().getQueryParams().getFirst("age");
            // 2、判断是否为空
            if (StringUtils.isNotEmpty(ageStr)){
                // 如果不为空，在对路由逻辑判断
                int age = Integer.parseInt(ageStr);
                return age <= config.maxAge && age >= config.minAge;
            }
            return false;
        };
    }

    public static class Config {
        private int minAge;
        private int maxAge;

        public int getMinAge() {
            return minAge;
        }

        public void setMinAge(int minAge) {
            this.minAge = minAge;
        }

        public int getMaxAge() {
            return maxAge;
        }

        public void setMaxAge(int maxAge) {
            this.maxAge = maxAge;
        }
    }

}
